﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Web.Security;

namespace DNA.Mvc.Controllers
{
    public class SocialNetworkController : Controller
    {
        IEventScoreRepository eventScoreRepository;
        IDataContext dataContext;

        public SocialNetworkController(IEventScoreRepository eventRepository, IDataContext dataContext)
        {
            eventScoreRepository = eventRepository;
            this.dataContext = dataContext;
        }

        [SiteControlPanel(Group = "Community", ResKey = "RES_SCORES", ShowInTopSiteOnly = true)]
        public ActionResult Scores()
        {
            return View(eventScoreRepository.All());
        }

        [Authorize, HttpPost]
        public ActionResult Scores(FormCollection forms)
        {
            var events = eventScoreRepository.All();

            foreach (var key in forms.AllKeys)
            {
                var e = eventScoreRepository.Find(key);
                if (e != null)
                {
                    e.Points = int.Parse(forms[key]);
                    eventScoreRepository.Update(e);
                }
            }

            return RedirectToAction("Scores");
        }

        [HttpPost, ValidateAntiForgeryToken]
        public void MailTo(string from, string to, string subject, string body)
        {
            var sb = new StringBuilder();
            if (!Request.IsAuthenticated)
            {
                sb.AppendFormat("<p> {0} ({1}) send you a message through {2} </p>", from, Request.UserHostAddress, UrlResolver.Resolve(HttpContext))
                    .AppendLine("<br/>")
                    .AppendLine("<hr /><p>")
                    .AppendLine(body)
                    .AppendLine("</p>");
            }
            else
            {
                var user = Membership.GetUser(User.Identity.Name);
                sb.AppendFormat("<p> {0} send you a message through {1} </p>", user.GetDisplayName(), UrlResolver.Resolve(HttpContext))
                   .AppendLine("<br/>")
                   .AppendLine("<hr /><p>")
                   .AppendLine(body)
                   .AppendLine("</p>");
            }

            if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body))
                WebMail.Send(WebSiteContext.Current.RootWeb.Title, to, subject, sb.ToString());
        }

        //public ActionResult Invite(string username)
        //{
        //    var friend = new Friend() 
        //    {
        //        UserName = User.Identity.Name,
        //        FriendName = username 
        //    };
        //}
    }
}
